<template>
  <div class="h-screen flex flex-col ">
    <div class="bg-white p-6 rounded-lg shadow-sm mb-6 overflow-y-auto flex-1 " id="body">
    <!-- 操作区 -->
    <div class="flex  justify-between mb-6 mt-6 relative">
        <div class="flex  space-x-6">
          <button class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded"  @click="showAddUserModal = true">
           <i class="fa fa-plus"></i> 添加用户
          </button>
          <button class="bg-gray-800 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded" @click="upUser">
           <i class="fa fa-upload"></i> 批量导入
          </button>
          <button class="bg-red-500 hover:bg-red-800 text-white font-bold py-2 px-4 rounded" @click="delUser">
            <i class="fa fa-trash"></i> 批量删除
          </button>
          </div>
          <div class="flex items-center">
            <div class="ml-8 relative">
          <input type="text" placeholder="搜索用户" 
                 class="pl-10 pr-4 py-2 border rounded-lg w-64 focus:outline-none focus:ring-2 focus:ring-blue-500">
          <i class="fas fa-search absolute left-3 top-3 text-gray-400" @click="searchUser"></i>
        </div>
          </div>
        </div>
        <!-- 新增用户框 -->
        <div class="absolute" id="addUserModal" v-if="showAddUserModal">
     <div class="bg-green-900 p-6 rounded-lg shadow-sm mb-6 w-130 " >
      <h1 id="bt" class=" font-bold text-white ">{{ isEditMode ? '编辑用户' : '新增用户' }}</h1>
      <!-- 编辑模式 -->
      <div v-if="isEditMode" class="text-yellow-100 text-sm mb-2">
        正在编辑用户：{{ newuser.username }}
      </div>
      <!-- 表单 -->
       <form @submit.prevent="submitUserForm">
        <label class="block text-sm font-medium text-white mb-1 ">用户姓名</label>
        <input id="yourInput" type="text" placeholder="请输入用户姓名" v-model="newuser.name" class="bg-white-100" >
        <label class="block text-sm font-medium text-white mb-1 ">用户部门</label>
        <input id="yourInput" type="text" placeholder="请输入部门" v-model="newuser.department" class="bg-white-100">
        <label class="block text-sm font-medium text-white mb-1 ">用户名</label>
        <input  id="yourInput" type="text" placeholder="请输入用户名" v-model="newuser.username" class="bg-white-100">
        <div>
          <label class="block text-sm font-medium text-white mb-1 ">用户角色</label>
            <select class="w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white-100" v-model="newuser.role">
            <option value="管理员">管理员</option>
            <option value="VIP用户">VIP用户</option>
            <option value="普通用户">普通用户</option>
           </select>
          </div>
          <div>
          <label class="block text-sm font-medium text-white mb-1 ">用户状态</label>
          <select  class="w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white-100" v-model="newuser.status">
            <option value="启用">启用</option>
            <option value="禁用">禁用</option>
          </select>
        </div>
        
        <div class="flex justify-center space-x-6 mt-6" >
          <button type="button" @click="closeModal" 
                  class="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-50 rounded-md">
            取消
        </button>
          <button type="submit" 
                  class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
            确认添加
          </button>
        </div>
        </form>
       </div></div>
        <!-- 表格 -->
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-4 text-left">
                <input type="checkbox" class="rounded" v-model="allSelected" />
              </th>
              <th class="px-4 py-4 text-left">用户名</th>
              <th class="px-4 py-4 text-left">姓名</th>
              <th class="px-4 py-4 text-left">部门</th>
              <th class="px-4 py-4 text-left">角色</th>
              <th class="px-4 py-4 text-left">状态</th>
              <th class="px-4 py-4 text-left">创建时间</th>
              <th class="px-4 py-4 text-left">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(user, index) in pagedUsers" :key="index" class="border-b hover:bg-gray-50">
              <td class="px-4 py-4">
                <input type="checkbox" class="rounded" v-model="user.selected" />
              </td>
              <td class="px-4 py-4">{{ user.username }}</td>
              <td class="px-4 py-4">{{ user.name }}</td>
              <td class="px-4 py-4">{{ user.department }}</td>
              <td class="px-4 py-4">{{ user.role }}</td>
              <td class="px-4 py-4">
                <span 
                  class="px-2 py-1 rounded-full text-sm"
                  :class="user.status === '启用' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                >
                  {{ user.status }}
                </span>
              </td>
              <td class="px-4 py-4">{{ user.createTime }}</td>
              <td class="px-4 py-4">
                <div class="flex space-x-2">
                  <button class="!rounded-button bg-blue-100 text-blue-500 px-4 py-2  whitespace-nowrap" @click="upthisUser(user)">
                    <i class="fas fa-edit"></i>
                  </button>
                  <button class="!rounded-button bg-red-100 text-red-500 px-4 py-2  whitespace-nowrap"  @click="delthisUser">
                    <i class="fas fa-trash "></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <!-- 分页 -->
        <div class="flex justify-between mb-6 mt-6">
            <div>共{{ total }}条数据</div>
            <div>每页{{ pageSize }}条</div>
            <div>当前{{ currentPage }}页</div>
            <div class="flex items-center">
                <button class="bg-gray-100 hover:bg-gray-700 text-black font-bold py-2 px-4 rounded" :disabled="currentPage ===1" @click="prevPage">上一页</button>
                <button 
              v-for="page in pages" 
              :key="page"
              class="!rounded-button px-4 py-2 border border-gray-300 whitespace-nowrap"
              :class="currentPage === page ? 'bg-gray-800 text-white' : 'hover:bg-gray-50'"
              @click="goToPage(page)"
            >
              {{ page }}
            </button>
                <button class="bg-gray-100 hover:bg-gray-700 text-black font-bold py-2 px-4 rounded" :disabled="currentPage === totalPages" @click="nextPage">下一页</button>
            </div>
          </div>
   </div>
     </div>
</template>

<script setup>
//torow 函数将对象转换为数组
import { ref, computed, reactive ,toRaw} from 'vue'
/**分页相关 */
// 分页相关响应式数据
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(30)

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
//页数计算函数
const pages = computed(() => 
  Array.from({ length: totalPages.value }, (_, i) => i + 1)
)

// 分页后的用户数据
const pagedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return users.slice(start, end)
})
const showAddUserModal = ref(false);
const newuser = reactive({
  username: '',
  name: '',
  department: '',
  role: '',
  status: '启用',
});
// 关闭模态框且重置表单
const closeModal = () => {
  showAddUserModal.value = false;
  isEditMode.value = false
  editingUserId.value = null
  setTimeout(() => {
    Object.assign(newuser, {
      username: '',
      name: '',
      department: '',
      role: '',
      status: '启用',
      tempId: null
    })
  }, 300)
};

const users = reactive(JSON.parse(localStorage.getItem('users') || '[]') || []);
const errors = reactive({
  username: '',
  name: '',
  department: '',
  role: '',
  
});
const submitUserForm = () => {
  // 清空错误信息
  errors.username = '';
  errors.name = '';
  errors.department = '';
  errors.role = '';

  // 简单验证
  if (!newuser.username.trim()) {
    errors.username = '请输入用户名';
    return;
  }
  if (!newuser.name .trim()) {
    errors.name = '请输入姓名';
  }
  if (!newuser.department.trim()) {
    errors.department = '请输入部门';
    return;
  }
  if (!newuser.role.trim()) {
    errors.role = '请输入角色';
    return;
  }
//修改用户逻辑
 if (isEditMode.value) {
    // 查找要修改的用户索引
    const index = users.findIndex(u => u.username === newuser.originalUsername)
    if (index > -1) {
      const updatedUser = {
        ...users[index],
        ...newuser,
        // 保留原始创建时间
        createTime: users[index].createTime,
        // 清除临时字段
        originalUsername: undefined
      }
      
      // 删除临时字段避免存入数据
      delete updatedUser.originalUsername
      
      users.splice(index, 1, updatedUser)
      localStorage.setItem('users', JSON.stringify(toRaw(users)))
      closeModal()
    }
  } else {
    /** 新增用户 */

  const newUser = {
    username: newuser.username,
    name:  newuser.name,
    department: newuser.department,
    role: newuser.role,
    status: newuser.status,
    createTime:new Date().toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit', 
      hour: '2-digit', 
      minute: '2-digit', 
      hour12: false }),
    selected: newuser.selected
  }
  users.push(newUser)
  localStorage.setItem('users', JSON.stringify(toRaw(users)))
  closeModal()
  }
 
}


/** 批量导入用户 */
const upUser = () => {
  const newUsers = [
    {
      username: 'user12',
      name: '用户12',
      department: 'IT部',
      role: '普通用户',
      status: '启用',
      createTime: '2021-01-12 12:00:00',
      selected: false
    },
    {
      username: 'user13',
      name: '用户13',
      department: '财务部',
      role: '普通用户',
      status: '启用',
      createTime: '2021-01-13 12:00:00',
      selected: false
    },
    {
      username: 'user14',
      name: '用户14',
      department: '销售部',
      role:'普通用户',
      status: '启用',
      createTime: '2021-01-14 12:00:00',
      selected: false
    }]
    //
    users.push(...newUsers)
  localStorage.setItem('users', JSON.stringify(toRaw(users))) 
  currentPage.value = 1
}
  // 分页方法
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const goToPage = (page) => {
  currentPage.value = page
}

/** 全选/全不选 */
const allSelected = computed({
  /**检测是否全选并返回表头布尔值 */
  get: () => {
    return users.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    ).every(user => user.selected)
    
  },
  // 设置当前页的全选状态
  set: (val) => {
    users.forEach((user, index) => {
      if (index >= (currentPage.value - 1) * pageSize.value && 
          index < currentPage.value * pageSize.value) {
        user.selected = val
      }
    })
  }
})

/** 批量用户删除 */
const delUser = () => {
  const selectedUsers = users.filter(user => user.selected)
  if (selectedUsers.length === 0) {
    alert('请先选择要删除的用户')
    return
  }
  const confirm = window.confirm(`啊！确认删除 ${selectedUsers.length} 个用户?`)
  if (confirm) {
    selectedUsers.forEach(user => {
      const index = users.indexOf(user)
      users.splice(index, 1)
      // 删除后更新存储
    localStorage.setItem('users', JSON.stringify(toRaw(users)))
    currentPage.value = 1
    })
  }
}
/**删除单个用户 */
const delthisUser = (user) => {
  const index = users.indexOf(user)
  users.splice(index, 1)
  // 更新存储
  localStorage.setItem('users', JSON.stringify(toRaw(users)))
  currentPage.value = 1
}
/** 修改单个用户 */
const isEditMode = ref(false)
const editingUserId = ref(null)
const upthisUser = (user) => {
  isEditMode.value = true
  showAddUserModal.value = true
  // 使用扩展运算符复制用户数据
  Object.assign(newuser, {
    ...user,
    originalUsername: user.username
  })
}

</script>

<style  scoped>
.h-screen { height: 100vh; }  /* 确保容器占满视口 */
.overflow-y-auto { overflow-y: auto; } /* 内容溢出时显示滚动条 */
th {
  padding-left: 1rem;
  padding-right: 1rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  text-align: left;
  font-weight: 500;
  color: #374151;
}
#addUserModal {
  margin-left: 20%;
}
#yourInput {
  margin-bottom: 10px;
  width: 100%;
  height: 30px;
  border-radius: 5px;
  border: #374151 1px solid;
}
#bt{
  text-align: center;
  font-size: 30px;
}
</style>